/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package uk.co.samuelwall.materialtaptargetprompt.sample.utils;

import ohos.agp.components.Component;
import ohos.app.Context;

/**
 * 工具类
 *
 * @since 2021-06-21
 */
public class Utils {
    /**
     * dp转化为px
     *
     * @param dp dp
     * @param context context
     * @return px
     */
    public static int dpToPx(float dp, Context context) {
        float scale = context.getResourceManager().getDeviceCapability().screenDensity;
        return (int) (dp * scale / NumUtil.INT_160 + NumUtil.FLOAT_05);
    }

    /**
     * 组件相对顶部的距离
     *
     * @param myView 目标组件
     * @return 相对顶部的距离
     */
    public static int getRelativeTop(Component myView) {
        if (myView.getComponentParent() == null) {
            return myView.getTop();
        } else {
            return myView.getTop() + getRelativeTop((Component) myView.getComponentParent());
        }
    }

    /**
     * 组件相对左边的距离
     *
     * @param myView 目标组件
     * @return 相对左边的距离
     */
    public static int getRelativeLeft(Component myView) {
        if (myView.getComponentParent() == null) {
            return myView.getLeft();
        } else {
            return myView.getLeft() + getRelativeLeft((Component) myView.getComponentParent());
        }
    }

    /**
     * 颜色转化rgba
     *
     * @param colorStr 颜色
     * @return rgba
     */
    public static String rgba(String colorStr) {
        return colorStr.length() == NumUtil.INT_7 ? colorStr + "FF" : colorStr;
    }

    /**
     * 颜色转化argb
     *
     * @param colorStr 颜色
     * @return argb
     */
    public static String argb(String colorStr) {
        return colorStr.length() == NumUtil.INT_7 ? "#FF" + colorStr.replace("#", "")
                : "#"
                        + colorStr.substring(colorStr.length() - NumUtil.INT_2)
                        + colorStr.substring(0, colorStr.length() - NumUtil.INT_2).replace("#", "");
    }

    /**
     * 颜色转化argb
     *
     * @param colorStr 颜色
     * @param alpha 透明度
     * @return argb
     */
    public static String argb(String colorStr, String alpha) {
        return colorStr.length() == NumUtil.INT_7
                ? "#" + alpha + colorStr.replace("#", "")
                : "#" + alpha + colorStr.substring(0, colorStr.length() - NumUtil.INT_2).replace("#", "");
    }
}
